package com.cheer.ba.view.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.CodeStatus;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.MineFragItemModel;
import com.cheer.ba.presenter.impl.LoginPresenter;
import com.cheer.ba.utils.ImageUtils;
import com.cheer.ba.utils.NotificationsUtils;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.view.activity.AddMyCloudBooks;
import com.cheer.ba.view.activity.DriversListAty;
import com.cheer.ba.view.activity.LookMyBillAty;
import com.cheer.ba.view.activity.MyCardGroupAty;
import com.cheer.ba.view.activity.MyDeviceAty;
import com.cheer.ba.view.activity.MyInvoicesAty;
import com.cheer.ba.view.activity.MyOrderAty;
import com.cheer.ba.view.activity.MyPointAty;
import com.cheer.ba.view.activity.NewCardPayAty;
import com.cheer.ba.view.activity.OilCardAty;
import com.cheer.ba.view.activity.PersonalAty;
import com.cheer.ba.view.activity.SettingAty;
import com.cheer.ba.view.activity.SuggestAty;
import com.cheer.ba.view.activity.TransitAty;
import com.cheer.ba.view.base.BaseCommFrg;
import com.cheer.ba.view.base.CommonAdapter;
import com.cheer.ba.view.base.IViewController;
import com.cheer.ba.view.base.ViewHolder;
import com.cheer.ba.view.dialog.DialogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 我的
 */
public class MineFrg extends BaseCommFrg implements AdapterView.OnItemClickListener, View.OnClickListener {

    //头像
    ImageView mImgUserHead;
    //昵称
    TextView mTxtUserName;
    //会员号
    TextView mTxtUserMember;


    @BindView(R.id.id_focus_listv)
    ListView myListView;
    private List<MineFragItemModel> mItems = new ArrayList<MineFragItemModel>();
    CommonAdapter<MineFragItemModel> mFocusAdapter;

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.frg_mine, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new LoginPresenter();
    }

    @Override
    public void initView() {
        initHeadView();
        MineFragItemModel item0 = new MineFragItemModel("企业认证", R.drawable.ic_my_account, "", "", "", false, true, true);
        MineFragItemModel item7 = new MineFragItemModel("我的车辆", R.drawable.ic_my_device, "", "", "", false, false, true);
        MineFragItemModel item1 = new MineFragItemModel(getString(R.string.invoice_manager), R.drawable.ic_my_invoice, "", "", "", false, true, true);
        MineFragItemModel item2 = new MineFragItemModel(getString(R.string.ic_cloud_record), R.drawable.ic_mine_book, "", "", "", false, false, true);
        MineFragItemModel item3 = new MineFragItemModel(getString(R.string.kefu_phone), R.drawable.ic_customer, "400 863 1886", "", "", false, true, true);
        MineFragItemModel item4 = new MineFragItemModel(getString(R.string.mine_ask_question), R.drawable.ic_mine_suggest, "", "", "", false, false, true);
//        MineFragItemModel item5 = new MineFragItemModel(getString(R.string.frequently_use_address), R.drawable.ic_common_address, "", "", "", false, false, true);
        MineFragItemModel item6 = new MineFragItemModel(getString(R.string.mine_setting), R.drawable.ic_mine_set, "", "", "", false, false, true);
        mItems.add(item0);
        mItems.add(item7);
        mItems.add(item1);
        mItems.add(item2);
        mItems.add(item3);
        mItems.add(item4);
//        mItems.add(item5);
        mItems.add(item6);
        EventBus.getDefault().register(this);
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    /**
     * 初始化头布局
     */
    private void initHeadView() {
        View mHeadView = LayoutInflater.from(frg).inflate(R.layout.layout_mine_head_listv, null);
        mImgUserHead = (ImageView) mHeadView.findViewById(R.id.id_mine_user_head_img);
        mTxtUserName = (TextView) mHeadView.findViewById(R.id.id_user_name_txt);
        mTxtUserMember = (TextView) mHeadView.findViewById(R.id.id_user_member_txt);
        mImgUserHead.setOnClickListener(this);
        mHeadView.findViewById(R.id.id_mine_oil_cards_txt).setOnClickListener(this);
        mHeadView.findViewById(R.id.id_mine_orders_txt).setOnClickListener(this);
        mHeadView.findViewById(R.id.id_mine_points_txt).setOnClickListener(this);
        mHeadView.findViewById(R.id.id_user_point_view).setOnClickListener(this);
        mHeadView.findViewById(R.id.id_user_sign_view).setOnClickListener(this);
        myListView.addHeaderView(mHeadView);
        setUserInfo();
    }

    @Override
    public void initData() {
        mFocusAdapter = new CommonAdapter<MineFragItemModel>(frg, mItems, R.layout.adp_mine_frg) {
            @Override
            public void convert(ViewHolder helper, MineFragItemModel item) {
                if (item.getDrawable() != 0) {
                    helper.getViewById(R.id.id_icon_img).setVisibility(View.VISIBLE);
                    helper.setImageResource(R.id.id_icon_img, item.getDrawable());
                } else {
                    helper.getViewById(R.id.id_icon_img).setVisibility(View.GONE);
                }
                helper.setText(R.id.id_name_txt, item.getName());
                //描述
                TextView mTxtDesc = (TextView) helper.getViewById(R.id.id_right_des_txt);
                //头像
                ImageView mHeadImg = (ImageView) helper.getViewById(R.id.id_person_head_img);
                //通知数量
                TextView mTxtNum = (TextView) helper.getViewById(R.id.id_contact_num_update);
                if (!StringUtils.isEmpty(item.getmDesc())) {
                    mTxtDesc.setVisibility(View.VISIBLE);
                    mTxtDesc.setText(item.getmDesc());
                    mTxtDesc.setTextColor(getResources().getColor(R.color.color_main));
                } else {
                    mTxtDesc.setVisibility(View.GONE);
                }
                if (!StringUtils.isEmpty(item.getmHead())) {
                    mHeadImg.setVisibility(View.VISIBLE);
                    ImageUtils.showRoundImg(frg, Session.getUserPicUrl(), R.drawable.ic_user_head, R.drawable.ic_user_head, mHeadImg);
                } else {
                    mHeadImg.setVisibility(View.GONE);
                }
                if (item.isUpdate()) {
                    mTxtNum.setVisibility(View.VISIBLE);
                    if (!StringUtils.isEmpty(item.getmNum())) {
//                        mTxtNum.setBackgroundResource(R.drawable.ic_update_red_point);
                        mTxtNum.setText(item.getmNum());
                    } else {
//                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(DensityUtils.px2dip(frg, 30), DensityUtils.px2dip(frg, 30));
//                        mTxtNum.setLayoutParams(params);
//                        mTxtNum.setBackgroundResource(R.drawable.shape_dot_red);
                        mTxtNum.setText("");
                    }
                } else {
                    mTxtNum.setVisibility(View.GONE);
                }
                if (item.isArrow()) {
                    helper.getViewById(R.id.id_right).setVisibility(View.VISIBLE);
                } else {
                    helper.getViewById(R.id.id_right).setVisibility(View.GONE);
                }
                if (item.isDivider()) {
                    helper.getViewById(R.id.id_line_v).setVisibility(View.VISIBLE);
                    helper.getViewById(R.id.id_divider_v).setVisibility(View.GONE);
                } else {
                    helper.getViewById(R.id.id_line_v).setVisibility(View.GONE);
                    helper.getViewById(R.id.id_divider_v).setVisibility(View.VISIBLE);
                }
            }
        };
        myListView.setAdapter(mFocusAdapter);
        myListView.setOnItemClickListener(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(BaseEvent event) {
        //返回类型
        String type = event.type;
        if (TextUtils.equals(type, IntentKey.Login.KEY_LOGIN_SUCCESS)) {
            setUserInfo();
        } else if (TextUtils.equals(type, IntentKey.Login.KEY_APP_EXIT)) {
            //退出app
            Session.clearShareP();
            mImgUserHead.setImageResource(R.drawable.ic_user_head);
            mTxtUserName.setText(getString(R.string.no_login));
            mTxtUserMember.setVisibility(View.GONE);
        } else if (TextUtils.equals(type, IntentKey.Login.KEY_MODIFY_LOGIN_PW)) {
            //修改登录密码成功
            Session.clearShareP();
            mImgUserHead.setImageResource(R.drawable.ic_user_head);
            mTxtUserName.setText(getString(R.string.no_login));
            mTxtUserMember.setVisibility(View.GONE);
            isLogin(false);
        } else if (TextUtils.equals(IntentKey.Upgrade.KEY_HAD_UPDATE, event.type)) {
            MineFragItemModel model = mItems.get(5);
            model.setUpdate(true);
            model.setmNum("");
            mFocusAdapter.notifyDataSetChanged();
        } else if (TextUtils.equals(IntentKey.Upgrade.KEY_NO_UPDATE, event.type)) {
            MineFragItemModel model = mItems.get(5);
            model.setUpdate(false);
            model.setmNum("");
            mFocusAdapter.notifyDataSetChanged();
        } else if (TextUtils.equals(IntentKey.Personal.KEY_PERSONAL_UPDATE, event.type)) {
            setUserInfo();
        }
    }

    /**
     * 设置用户信息
     */
    public void setUserInfo() {
        ImageUtils.showCircleImg(frg, Session.getUserPicUrl(), R.drawable.ic_user_head, R.drawable.ic_user_head, mImgUserHead);
        if (StringUtils.isEmpty(Session.getUserName())) {
            mTxtUserName.setText("未登录");
            mTxtUserMember.setVisibility(View.GONE);
        } else {
            mTxtUserName.setText(Session.getUserName());
            mTxtUserMember.setText("会员号：" + Session.getUserNo());
        }
    }

    /**
     * 检测是否有通知权限
     */
    private void checkMineNotification() {
        if (!NotificationsUtils.isNotificationEnabled(frg)) {
            Session.setUserFirstRemindAuth(false);
            DialogUtils.showCommDialog(frg, "开启消息通知，不错过任何重要消息。", "取消", "去设置", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DialogUtils.DialogDiss();
                    requestPermission(0);
                }
            });
            DialogUtils.DialogShow();
        }
    }

    @Override
    public void onClick(View mView) {
        switch (mView.getId()) {
            //我的积分
            case R.id.id_user_point_view:
                if (isLogin(true)) {
                    showActivity(frg, MyPointAty.class);
                }
                break;
            //签到
            case R.id.id_user_sign_view:
                if (isLogin(true)) {
                    ((LoginPresenter) presenter).userSign();
                }
                break;
            //点击登录
            case R.id.id_mine_user_head_img:
                if (isLogin(false)) {
                    showActivity(frg, PersonalAty.class);
                }
                break;
            //我的油卡
            case R.id.id_mine_oil_cards_txt:
                if (isLogin(true)) {
                    Intent card = new Intent(frg, OilCardAty.class);
                    card.putExtra(IntentKey.General.KEY_PAGE, false);
                    showActivity(frg, card);
                }
                break;
            //我的订单
            case R.id.id_mine_orders_txt:
                if (isLogin(true)) {
//                    showActivity(frg, MyOilCardAty.class);
                    showActivity(frg, MyOrderAty.class);
                }
                break;
            //我的优惠券
            case R.id.id_mine_points_txt:
                if (isLogin(true)) {
                    showActivity(frg, MyCardGroupAty.class);
                }
                break;
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.SIGN_SUCCESS)) {
                //签到成功
                String msg = (String) t;
                SVProgressHUD.showSuccessWithStatus(frg, msg);
                if (Session.getUserFirstRemindAuth()) {
                    checkMineNotification();
                }
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            //企业认证
            case 1:
                if (isLogin(true)) {
                    TransitAty.start2TransitAty(frg, IntentCode.General.JUMP_MY_INFO);
                }
                break;
            //我的车辆
            case 2:
                if (isLogin(true)) {
//                    showActivity(frg, MyDeviceAty.class);
                    showActivity(frg, DriversListAty.class);
                }
                break;
            //发票管理
            case 3:
                if (isLogin(true)) {
                    showActivity(frg, MyInvoicesAty.class);
                }
                break;
            //云记账
            case 4:
//                if (isLogin(true)) {
//                    showActivity(frg, AccountBookAty.class);
//                }
                if (isLogin(true)) {
                    if (Session.getUserBooks()) {
                        showActivity(frg, LookMyBillAty.class);
                    } else {
                        Intent intent = new Intent(frg, AddMyCloudBooks.class);
                        startActivityForResult(intent, IntentCode.Book.BOOK_REQUEST_CODE);
                    }
                }
                break;
            //客服电话
            case 5:
//                showCustomer();
                showActivity(frg, NewCardPayAty.class);
                break;
            //投诉建议
            case 6:
                if (isLogin(true)) {
                    showActivity(frg, SuggestAty.class);
                }
                break;
            //常用地址
//            case 5:
//                if (isLogin(true)) {
//                    if (Session.getDefaultAddress()) {
//                        showActivity(frg, FrequentlyAreasAty.class);
//                    } else {
//                        Intent address = new Intent(frg, FrequentlyAddressAty.class);
//                        startActivityForResult(address, IntentCode.Address.ADDRESS_REQUEST_CODE);
//                    }
//                }
//                break;
            //设置
            case 7:
                showActivity(frg, SettingAty.class);

        }
    }

    /**
     * 显示客服电话
     */
    private void showCustomer() {
        DialogUtils.showCommDialog(frg, "客服电话：400 863 1886", "取消", "拨打", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.DialogDiss();
                StringUtils.telPhone(frg, "400 863 1886");
            }
        });
        DialogUtils.DialogShow();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentCode.Address.ADDRESS_REQUEST_CODE) {
            if (resultCode == IntentCode.Address.ADDRESS_RESULT_CODE) {
//                showActivity(frg, FrequentlyAreasAty.class);
            }
        }
    }

    @Override
    public void onLoadingStatus(IViewController mView, boolean isHandler, int loadingStatus, int flag, String string) {
        if (loadingStatus == CodeStatus.Gegeneral.ERROR_DATA) {
            SVProgressHUD.showInfoWithStatus(frg, "拉取失败，稍后重试");
        }
        super.onLoadingStatus(mView, isHandler, loadingStatus, flag, string);
    }
}
